﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CollegeShop.WebProcessor;
using CollegeShop.Biz;
using CollegeShop.Tool.Framework;
using CollegeShop.Infrastructure.Entities.Entity;

namespace CollegeShop.Web.Controllers
{
    [ErrorHandle]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.SaleList = CommodityBiz.LoadSaleList();
            return View();
        }
        //public string CommodityDetail(int id)
        //{
        //    var detail = CommodityBiz.LoadCommodity(id);
        //    if (detail != null)
        //    {
        //        return detail.ToJson();
        //    }
        //    return "";
        //}
        public string SaleDetail(int saleId)
        {
            var detail = CommodityBiz.LoadAllCommodities(saleId);
            if (detail != null)
            {
                return new
                {
                    Standard = detail.GroupBy(c=>c.Standard).Select(c=>c.Key).ToList(),
                    Style = detail.GroupBy(c => c.Style).Select(c => c.Key).ToList(),
                    SdGroup = detail.GroupBy(c=>c.Standard).Select(c=>new {Key = c.Key, Contain=c.Select(o=>o.Style).ToList()}).ToList(),
                    SyGroup = detail.GroupBy(c=>c.Style).Select(c=>new {Key = c.Key,Contain=c.Select(o=>o.Standard).ToList()}).ToList(),
                    Data = detail
                }.ToJson();// detail.GroupBy(c => c.Standard).ToJson();
            }
            return "";
        }
        public ActionResult Forbidden()
        {
            return View();
        }
        public ActionResult Cart()
        {
            List<Goods> list = new List<Goods>();
            var cookie = Request.Cookies["goodscart"];
            if (cookie != null && !String.IsNullOrEmpty(cookie.Value)) 
            {
                List<string> idList = Server.UrlDecode(cookie.Value).Split(',').ToList().Distinct().ToList();
                if (idList.Any())
                {
                    foreach(var item in idList)
                    {
                        if (!String.IsNullOrEmpty(item))
                        {
                            int id = -1;
                            if (Int32.TryParse(item, out id))
                            {
                                var commodity = CommodityBiz.LoadCommodity(id);
                                if (commodity != null)
                                {
                                    list.Add(commodity);
                                }
                            }
                        }
                    }
                }
            }
            ViewBag.Commodities = list;
            return View();
        }
        public ActionResult ConfirmOrder(string items, int use = -1)
        {
            ViewBag.Items = items;
            ViewBag.Use = use;
            List<string> list = items.Split('$').ToList();
            decimal totalPrice = 0;
            foreach(var item in list)
            {
                if (String.IsNullOrEmpty(item))
                {
                    continue;
                }
                string[] segment = item.Split(':');
                int id = -1,count = 0;
                if (Int32.TryParse(segment[0], out id) && Int32.TryParse(segment[1], out count)) {
                    var commodity = CommodityBiz.LoadCommodity(id);
                    if (commodity != null) {
                        totalPrice += commodity.DefaultSalePrice * count;
                    }
                }
            }
            if (totalPrice == 0)
            {
                return Redirect("/");
            }
            ViewBag.TotalPrice = totalPrice;
            ViewBag.IsMember = false;
            if (HttpContext.User.Identity.IsAuthenticated) 
            {
                List<Deliveryaddress> addresses = UserBiz.LoadDeliveryAddresses(HttpContext.User.Identity.Name);
                ViewBag.DeliveryAddress = addresses;

                if (new User().Find(HttpContext.User.Identity.Name) != null)
                {
                    ViewBag.IsMember = true;
                }
            }
            ViewBag.Units =  BaseInfoBiz.GetSalesUnit();
            return View();
        }
        [HttpPost]
        public string SubmitOrder(string items,string tempAddress="", int address=-1)
        {
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                return SubmitOrderForLogined(items, address);
            }
            else
            {
                return SubmitOrderForGhost(items, tempAddress);
            }
        }

        private string SubmitOrderForLogined(string items, int address)
        {
            if (address <= 0)
            {
                return "对不起，请重新选择收回地址并重新提交订单！";
            }
            var delivery = UserBiz.CheckDeliveryAddresses(HttpContext.User.Identity.Name, address);
            if (delivery == null)
            {
                return "对不起，您选择的收货地址不存在，请重新选择！";
            }
            items = Server.UrlDecode(items);
            List<string> list = items.Split('$').ToList();
            List<OrderModel> goods = new List<OrderModel>();
            foreach (var item in list)
            {
                if (String.IsNullOrEmpty(item))
                {
                    continue;
                }
                string[] segment = item.Split(':');
                int id = -1, count = 0;
                if (Int32.TryParse(segment[0], out id) && Int32.TryParse(segment[1], out count))
                {
                    var commodity = CommodityBiz.LoadCommodity(id);
                    if (commodity != null)
                    {
                        goods.Add(new OrderModel()
                        {
                            goods = commodity,
                            Amount = count
                        });
                    }
                }
            }
            if (goods.Any())
            {
                if (CommodityBiz.SubmitOrder(goods, delivery) == null)
                {
                    return "您的收货地址已经失效，请重新填写";
                }
            }
            else
            {
                return "您没有选择任何商品，请重新确认订单";
            }
            return "ok";
        }

        private string SubmitOrderForGhost(string items, string address)
        {
            do
            {
                address = Server.UrlDecode(address);
            }
            while (address != Server.UrlDecode(address));

            if (String.IsNullOrEmpty(address))
            {
                return "对不起，请重新选择收回地址并重新提交订单！";
            }
            var delivery = address.ToObject<Deliveryaddress>();

            items = Server.UrlDecode(items);
            List<string> list = items.Split('$').ToList();
            List<OrderModel> goods = new List<OrderModel>();
            foreach (var item in list)
            {
                if (String.IsNullOrEmpty(item))
                {
                    continue;
                }
                string[] segment = item.Split(':');
                int id = -1, count = 0;
                if (Int32.TryParse(segment[0], out id) && Int32.TryParse(segment[1], out count))
                {
                    var commodity = CommodityBiz.LoadCommodity(id);
                    if (commodity != null)
                    {
                        goods.Add(new OrderModel()
                        {
                            goods = commodity,
                            Amount = count
                        });
                    }
                }
            }
            if (goods.Any())
            {
                if (CommodityBiz.SubmitOrder(goods, delivery, false) == null)
                {
                    return "您的收货地址已经失效，请重新填写";
                }
            }
            else
            {
                return "您没有选择任何商品，请重新确认订单";
            }
            return "ok";
        }

        [HttpPost]
        public ActionResult newDeliveryAddress(string items, string LinkMan, int saleunitID, string dormitory,
            string LinkPhone,string type)
        {
            var salesunit = new Salesunit().Find(saleunitID.ToString());
            if(salesunit == null)
            {
                return RedirectToAction("Cart");
            }
            var da = new Deliveryaddress()
            {
                SalesUnitID = salesunit.ID,
                Address = dormitory,
                UserName = HttpContext.User.Identity.Name,
                LinkMan = LinkMan,
                LinkPhone = LinkPhone,
                isDefault = false
            }.PostAdd();
            if (type == "saveanddefault")
            {
                UserBiz.UpdateDeliveryAddressNoDefault(HttpContext.User.Identity.Name);
                da.isDefault = true;
                da.PostModify();
            }

            return RedirectToAction("ConfirmOrder", new { items = items, use = type == "saveanduse" ? da.ID : -1 });
        }
        
        public int setdefaultdelivery(int id)
        {
            var da = new Deliveryaddress().Find(id.ToString());
            if (da != null)
            {
                UserBiz.UpdateDeliveryAddressNoDefault(HttpContext.User.Identity.Name);
                da.isDefault = true;
                da.PostModify();
                return 1;
            }
            return 0;
        }
        public int deletedeliveryitem(int id) 
        {
            var da = new Deliveryaddress().Find(id.ToString());
            if (da != null)
            {
                da.PostDelete();
                if (da.isDefault)
                {
                    var list = UserBiz.LoadDeliveryAddresses(HttpContext.User.Identity.Name);
                    if (list.Any())
                    {
                        var def = list.First();
                        def.isDefault = true;
                        def.PostModify();
                    }
                }
                return 1;
            }
            return 0;
        }
#if DEBUG
        public ActionResult AdminLogin()
        {
            System.Web.Security.FormsAuthentication.SetAuthCookie("51944179@qq.com", false);
            return Redirect("/");
        }
#endif
        public ActionResult error()
        {
            return View();
        }

    }
}
